<template>
    <el-container class="sys_task_job">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="queryData"
                                @event="handleHeaderEvent">
                </headerTemplate>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent" />
                </div>
            </el-card>
        </el-main>
        <component-dialog :options="componentDialogOptions" />
    </el-container>
</template>

<script>
import SvgIcon from "@common/components/SvgIcon";
import TaskJobForm from "../dialog/TaskJobForm";
import sysTaskJobApi from "@common/api/system/sysTaskJobApi";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "SysTaskJob",
    data() {
        let $this = this;
        return {
            modeList: [],
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            $this.getList();
                        },
                    },
                    {
                        id: "add",
                        label: '添加',
                        type: 'primary',
                        icon: "fa fa-plus",
                        show: true,
                        method: () => {
                            $this.showDialog();
                        },
                    },
                    {
                        id: "startQuartz",
                        type: 'success',
                        show: true,
                        render(h, params) {
                            return [
                                h(SvgIcon, {
                                    props: {
                                        iconClass: 'icon-start',
                                    },
                                }),
                                h('span', {
                                    style: {
                                        marginLeft: '3px',
                                    },
                                }, '启动'),
                            ];
                        },
                        method: () => {
                            $this.changeQuartzState(null, 1);
                        },
                    },
                    {
                        id: "stopQuartz",
                        type: 'danger',
                        show: true,
                        render(h, params) {
                            return [
                                h(SvgIcon, {
                                    props: {
                                        iconClass: 'icon-stop',
                                    },
                                }),
                                h('span', {
                                    style: {
                                        marginLeft: '3px',
                                    },
                                }, '停止'),
                            ];
                        },
                        method: () => {
                            $this.changeQuartzState(null, 0);
                        },
                    },
                ],
                toolbar_filter: [],
            },
            token: $this.$store.state.accessToken.token,
            account_set_sid: $this.$utils.getAccountSetSid(),
            dataList: [],
            tableOptions: {
                ref: "TaskJobTable",
                container: ".sys_task_job",
                multiSelect: true,
                columns: [
                    {
                        label: "所属模块",
                        prop: "mode",
                        align: "center",
                        width: 90,
                        formatter(row) {
                            let filter = $this.modeList.filter(item => item.value === row.mode);
                            if ($this.$utils.isNotEmptyList(filter)) {
                                return filter[0].display_text;
                            }
                            return '';
                        },
                    },
                    {
                        label: "编码",
                        prop: "code",
                        align: "center",
                    },
                    {
                        label: "名称",
                        prop: "name",
                        align: "center",
                    },
                    {
                        label: "任务类型",
                        prop: "task_type",
                        align: "center",
                        width: 90,
                        formatter: (row) => {
                            if ($this.$utils.isNotEmpty(row.task_type)) {
                                return row.task_type === 0 ? "simple" : "cron";
                            }
                            return '';
                        },
                    },
                    {
                        label: "间隔时间(ms)",
                        prop: "interval_time",
                        align: "center",
                        width: 120,
                        formatter: (row) => {
                            return row.task_type === 0 ? row.interval_time : "";
                        },
                    },
                    {
                        label: "cron表达式",
                        prop: "cron_clause",
                        align: "center",
                        formatter: (row) => {
                            return row.task_type === 0 ? "" : row.cron_clause;
                        },
                    },
                    {
                        label: "任务对象名",
                        prop: "job_object_name",
                        align: "center",
                    },
                    {
                        label: "任务方法名",
                        prop: "job_method_name",
                        align: "center",
                    },
                    {
                        label: "状态",
                        prop: "state",
                        align: "center",
                        width: 60,
                        formatter: (row) => {
                            return row.state === 1 ? '<span style="color:green;font-size:1.5em;">启用</span>' : "禁用";
                        },
                    },
                    {
                        label: "最近异常信息",
                        prop: "last_error",
                        align: "center",
                    },
                ],
                operates: {
                    list: [
                        {
                            id: "info",
                            icon: "fa fa-pencil",
                            type: "primary",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "编辑",
                            },
                            method: (index, row) => {
                                $this.showDialog(row, "edit");
                            },
                        },
                        {
                            id: "start",
                            type: "success",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "启动",
                            },
                            svg: {
                                iconClass: 'icon-start',
                            },
                            filter(row) {
                                return row.state !== 1;
                            },
                            method: (index, row) => {
                                $this.changeQuartzState(row, 1);
                            },
                        },
                        {
                            id: "stop",
                            type: "danger",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "停止",
                            },
                            svg: {
                                iconClass: 'icon-stop',
                            },
                            filter(row) {
                                return row.state === 1;
                            },
                            method: (index, row) => {
                                $this.changeQuartzState(row, 0);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
            selectionList: [],
            rules: {},
            searchValue: "",
            queryData: { dr: 0 },
            componentDialogOptions: {
                visible: false,
            },
        };
    },
    mounted() {
        this.initModeList();
        this.getList();
    },
    methods: {
        initModeList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindCommonParameterValuesByKey, {
                key1: 'account_mode',
            }).then(result => {
                _this.modeList = result.data || [];
            }).catch(() => {
            });
        },
        handleHeaderEvent(event) {
            const _this = this;
            _this.queryData = $.extend({}, _this.queryData, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        getList(init) {
            let $this = this;
            $this.dataList = [];
            if (init) {
                $this.tableOptions = $this.resetTablePagination($this.tableOptions);
            }
            let queryData = $this.getQueryParams($this.tableOptions, $this.queryData);
            queryData.resource_client = '1';
            sysTaskJobApi.findSysTaskJobs(queryData, result => {
                $this.dataList = result.data || [];
                $this.tableOptions = $this.setTableTotal($this.tableOptions, result);
            });
        },
        confirmDel(ids) {
            let $this = this;
            $this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                sysTaskJobApi.batchDelSysTaskJob({ ids }, () => {
                    $this.getList();
                    $this.$message.success("删除成功");
                });
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        changeQuartzState(row, state) {
            const _this = this;
            let sid_list = _this.selectionList.map(item => item.sid);
            if (!row) {
                if (!_this.checkSelection(_this.selectionList, true)) {
                    return;
                }
                let filter = _this.selectionList.filter(item => item.state === 1);
                if (state === 0) {
                    filter = _this.selectionList.filter(item => item.state === 0);
                }
                if (_this.$utils.isNotEmptyList(filter)) {
                    let nameList = filter.map(item => item.name);
                    _this.$message.error(`任务：${ nameList.join('、') } ${ state === 1 ? '已启动' : '未启动' }`);
                    return;
                }
            } else {
                sid_list = [ row.sid ];
            }
            let url = _this.$api.API_StartQuartz;
            if (state === 0) {
                url = _this.$api.API_StopQuartz;
            }
            _this.fetchData(url, { sid_list }).then(() => {
                _this.$message.success(`${ state === 1 ? '启动' : '停止' }成功`);
                _this.getList();
            }).catch(() => {
            });
        },
        showDialog(row, type) {
            let $this = this;
            if (!row) {
                row = {
                    state: 0,
                    task_type: 1,
                    interval_time: 60000,
                };
            }
            $this.componentDialogOptions = {
                visible: true,
                width: '600px',
                title: type === "add" ? "创建" : "编辑",
                component: TaskJobForm,
                propsData: {
                    row,
                },
                btns: [
                    {
                        type: 'primary',
                        text: '确定',
                        loading: true,
                        method(option, { component }) {
                            component && typeof component.saveOrUpdate === 'function' && component.saveOrUpdate().then(valid => {
                                if (valid) {
                                    option.visible = false;
                                    $this.getList();
                                }
                            })
                        },
                    }
                ],
            };
        },
        // 接收回调
        handleEvent(event) {
            let $this = this;
            if (event.type === "refresh") {
                $this.getList();
            }
        },
    },
};
</script>

<style lang="less" rel="stylesheet/less" scoped>
.sys_task_job {
    height: 100%;

    .top-card {
        height: 65px !important;
    }

    .buttons {
        margin: 0 0 10px 0;
    }

}
</style>
